<template>
  <div class="users-base-wrapper">
    <!-- 主要部分 -->
    <main class="user_main_part">
      <!-- 💭筛选框 -->
      <section class="users_input">
        <el-form ref="formRef" :model="formData" label-width="120px" style="width: 90%; margin: 0 auto">
          <el-row>
            <el-col v-for="item in formColumns" :key="item.prop" :span="8">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-input
                  v-if="item.ele === 'input'"
                  v-model="formData[item.prop]"
                  size="mini"
                  style="width: 90%"
                  maxlength="30"
                  placeholder="请输入"
                  clearable
                ></el-input>
                <el-select
                  v-if="item.ele === 'select'"
                  v-model="formData[item.prop]"
                  size="mini"
                  clearable
                  style="width: 90%"
                  maxlength="30"
                >
                  <el-option v-for="it in item.options" :key="it.value" :value="it.value" :label="it.label">{{
                    it.label
                  }}</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </section>
      <!-- 💭操作按钮 -->
      <section class="users_button">
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <el-button size="mini" @click="handleClear" icon="el-icon-refresh-left">重置</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          <el-button size="mini" type="primary" icon="el-icon-download" @click="handleDownLoad()">下载导入模版</el-button>
          <el-upload
            action
            style="margin-left: 8px"
            :http-request="handleImportGeneralEncoding"
            :file-list="fileList"
            :show-file-list="false"
          >
            <el-button type="primary" size="mini" :loading="importLoading" icon="el-icon-upload"> 导入 </el-button>
          </el-upload>
          <el-button type="primary" icon="el-icon-download" size="mini" style="margin-left: 8px" @click="handleDownLoadData">导出</el-button>
        </el-row>
      </section>
      <!-- 💭表格部分 -->
      <section class="users_table">
        <!-- 表格 -->
        <el-table :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :data="tableData" :stripe="true">
          <el-table-column label="姓名" align="center" prop="nickname"> </el-table-column>
          <el-table-column label="邮箱" align="center" prop="email"> </el-table-column>
          <el-table-column label="电话" align="center" prop="mobile"> </el-table-column>
          <el-table-column label="单位" align="center" prop="orgName"> </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === 0" type="warning">未激活</el-tag>
              <el-tag v-if="row.status === 1" type="success">激活</el-tag>
              <el-tag v-if="row.status === 2" type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所在项目数" align="center" prop="projectNum"> </el-table-column>
          <el-table-column label="用户角色" align="center" prop="time">
            <template v-slot="{ row }">
              <span v-for="item in row.roleList" :key="item.id">
                {{ item.name }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="是否启用" align="center" prop="status">
            <template v-slot="{ row }">
              <el-switch
                v-model="row.status"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="2"
                @change="handleSwitchChange($event, row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="最近一次登录时间" align="center" prop="lastLoginTime" width="150px">
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="180px">
            <template v-slot="{ row }">
              <el-button type="text" @click="handleEdit(row)">修改</el-button>
              <el-button type="text" @click="handleRenew(row)">重发邮件</el-button>
              <el-button type="text" @click="handleDelete(row)">删除</el-button>
              <el-button type="text" @click="handleReset(row)">修改密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="end" style="height: 60px" align="middle">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.pageNo"
            :page-sizes="[10, 20, 50]"
            :page-size="pageParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </section>
    </main>
    <!-- 新增框 -->
    <UsersAddDia ref="UsersAddDia" :addVis.sync="addVis" @createUserData="createUserData"> </UsersAddDia>
    <!-- 编辑框 -->
    <UsersEditDia
      ref="UsersEditDia"
      :editVis.sync="editVis"
      :editDataProp="editDataProp"
      @updateUserData="updateUserData"
    ></UsersEditDia>
    <!-- 修改密码弹窗 -->
    <UserChangePassword
      ref="UserChangePassword"
      :changeDiaVis.sync="changeDiaVis"
      @changeUserPass="changeUserPass"
    ></UserChangePassword>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import UsersAddDia from './components/UsersAddDia.vue'
import UsersEditDia from './components/UsersEditDia.vue'
import UserChangePassword from './components/UserChangePassword.vue'
import { handleExportResponse } from '@/utils/index'
export default {
  name: 'users-manage',
  components: {
    UsersAddDia,
    UsersEditDia,
    UserChangePassword,
  },
  data() {
    return {
      // 表单规则
      formColumns: [
        { ele: 'input', label: '姓名：', prop: 'username' },
        { ele: 'input', label: '邮箱：', prop: 'email' },
        { ele: 'input', label: '单位：', prop: 'orgName' },
        {
          ele: 'select',
          label: '账号状态：',
          prop: 'status',
          options: [
            { value: '0', label: '未激活' },
            { value: '1', label: '激活' },
            { value: '2', label: '禁用' },
          ],
        },
        {
          ele: 'select',
          label: '角色：',
          prop: 'roleId',
          options: [],
        },
      ],
      // 表单数据
      formData: {
        username: '',
        email: '',
        orgName: '',
        status: '',
        roleId: '',
      },
      // 表格数据
      tableData: [],
      addVis: false,
      editVis: false,
      changeDiaVis: false,
      editDataProp: {},
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      changePassId: '',
      fileList: [],
      importLoading: false,
    }
  },

  created() {
    this.getUserData()
    this.getRoleData()
  },
  mounted() {},

  methods: {
    ...mapActions('usersManage', [
      'getUserDataAPI',
      'deleteUserDataAPI',
      'updateUserDataAPI',
      'createUserDataAPI',
      'changePasswordAPI',
      'downloadUserTemplateAPI',
      'importUserAPI',
      'exportUserAPI',
    ]),
    ...mapActions('roleManage', ['getRoleDataAPI']),
    // 修改用户密码
    async changeUserPass(newPassword) {
      const data = {
        newPassword: newPassword,
        id: this.changePassId,
      }
      const res = await this.changePasswordAPI({ data })
      if (res.code === 200) {
        this.$message.success('修改成功')
        this.$refs.UserChangePassword.publicClose()
      }
    },
    // 获取角色
    getRoleData() {
      this.getRoleDataAPI().then(res => {
        const arr = res.data.records.map(item => {
          return {
            label: item.name,
            value: item.id,
          }
        })
        this.formColumns[4].options = arr
      })
    },
    // 获取表格数据
    getUserData() {
      const params = {
        ...this.formData,
        ...this.pageParams,
      }
      this.getUserDataAPI({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.total = data.total
          this.pageParams.pageNo = data.current
          this.tableData = data.records
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    handleEdit(row) {
      this.editVis = true
      this.editDataProp = { ...row }
    },
    // 点击重发
    handleRenew(row) {
      this.$message.warning('功能开发中！')
    },
    // 点击删除
    handleDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 用户点击了确定按钮，执行相应的操作
          const params = {
            id: row.id,
          }
          this.deleteUserDataAPI({ params }).then(res => {
            const { code, message } = res
            if (code === 200) {
              this.$message.success('删除成功')
              const pageLastOne =
                this.total % this.pageParams.pageSize === 1 &&
                Math.floor(this.total / this.pageParams.pageSize) === this.pageParams.pageNo - 1
              if (pageLastOne) {
                if (this.pageParams.pageNo !== 1) {
                  this.pageParams.pageNo = this.pageParams.pageNo - 1
                }
              }
              this.getUserData()
            } else {
              this.$message.error(message || '服务异常，请稍后重试!')
            }
          })
        })
        .catch(() => {})
    },
    // 点击重置密码
    handleReset(row) {
      this.changeDiaVis = true
      this.changePassId = row.id
    },
    handleSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getUserData()
    },
    handleClear() {
      this.$refs.formRef.resetFields()
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.total = 0
      this.getUserData()
    },
    handleAdd() {
      this.addVis = true
    },
    // 💭下载
    async handleDownLoad() {
      const res = await this.downloadUserTemplateAPI()
      handleExportResponse(res.data, '用户_导入模版')
    },
    // 💭导入
    handleImportGeneralEncoding(file) {
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', file.file)
      // 导入请求
      this.importUserAPI({ data: formData })
        .then(res => {
          this.importLoading = false
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '导入成功' + res.message,
            })
            this.fileList.push({ name: file.file.name, url: res.data })
            // 获取表格数据
            this.getUserData()
          } else {
            this.$message({
              type: 'error',
              message: '导入数据失败，请稍后重试~',
            })
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 💭导出数据
    handleDownLoadData() {
      const data = {
        ...this.formData,
      }
      this.exportUserAPI({ data }).then(res => {
        const { data } = res
        handleExportResponse(data, '用户_列表')
      })
    },
    // 启用按钮
    handleSwitchChange(val, row) {
      const data = {
        userList: [
          {
            id: row.id,
            status: val,
          },
        ],
      }
      this.updateUserDataAPI({ data }).then(res => {
        const { code, message } = res
        if (code === 200) {
          this.$message.success('修改成功')
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },
    // 创建用户
    createUserData(payload) {
      const data = {
        ...payload,
      }
      this.createUserDataAPI({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('创建成功')
          this.getUserData()
          this.$refs.UsersAddDia.publicClose()
        }
      })
    },
    // 修改用户
    updateUserData(payload) {
      const data = {
        ...payload,
      }
      this.updateUserDataAPI({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('修改成功')
          this.getUserData()
          this.$refs.UsersEditDia.publicClose()
        }
      })
    },
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getUserData()
    },
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getUserData()
    },
  },
}
</script>
<style lang="scss" scoped>
.users-base-wrapper {
  height: 100%;
  background-color: $white;
  .user_main_part {
    background-color: $white;
    padding: 12px;
    .users_input {
      margin-top: 12px;
    }
    .users_button {
      margin-top: 12px;
      margin-left: 48px;
      .el-button {
        border-radius: 10%;
        margin-right: 8px;
      }
    }
    .users_table {
      margin-top: 24px;
    }
  }
}
</style>
